"""
实现访问计数器的中间件
"""
class VistCOunterMiddleware:
    def __init__(self,get_response):
        self.get_response = get_response
        # 初始化计数器
        self.count = 0
        
    def __call__(self,request):
        # 请求处理前 -- 计数器+1
        self.count += 1
        # 记录当前访问网站的 ip 地址
        ip_address = self.get_client_ip(request)
        print(f"当前访问的 ip 地址:{ip_address}")
        print(f"当前访问次数:{self.count}")
        
        # 继续处理请求
        response = self.get_response(request)
        
        # 请求处理后
        return response
    
    def get_client_ip(self, request):
        # 获取客户端的真实 ip 地址
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.spilit(',')[0]
        else:
            ip = request.META.get("REMOTE_ADDR")
        return ip